'''Train CIFAR10 with PyTorch.'''
from multiprocessing import freeze_support

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn

import torchvision
import torchvision.transforms as transforms
from torch.optim.lr_scheduler import MultiStepLR

import os
import argparse

from models import *
from utils import progress_bar




device = 'cuda' if torch.cuda.is_available() else 'cpu'
best_acc = 0  # best test accuracy
start_epoch = 0  # start from epoch 0 or last checkpoint epoch

# Data
print('==> Preparing data..')
transform_train = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])

transform_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=4)

testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')





# Training
def train(epoch,net,criterion,optimizer):
    print('\nEpoch: %d' % epoch)
    net.train()
    train_loss = 0
    correct = 0
    total = 0
    for batch_idx, (inputs, targets) in enumerate(trainloader):
        inputs, targets = inputs.to(device), targets.to(device)
        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()

        train_loss = train_loss*0.8+0.2*loss.item()
        _, predicted = criterion(outputs).max(1)
        total += targets.size(0)
        correct += predicted.eq(targets).sum().item()

        progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
            % (train_loss, 100.*correct/total, correct, total))

        # if batch_idx>10: break

    return train_loss, 100.*correct/total

def test(epoch,net,criterion,optimizer):
    global best_acc
    net.eval()
    test_loss = 0
    correct = 0
    total = 0
    with torch.no_grad():
        for batch_idx, (inputs, targets) in enumerate(testloader):
            inputs, targets = inputs.to(device), targets.to(device)
            outputs = net(inputs)
            loss = criterion(outputs, targets)

            test_loss += loss.item()
            _, predicted = criterion(outputs).max(1)
            total += targets.size(0)
            correct += predicted.eq(targets).sum().item()

            progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
                % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))

    # Save checkpoint.
    acc = 100.*correct/total
    return test_loss/(batch_idx+1),acc
    # if acc > best_acc:
    #     print('Saving..')
    #     state = {
    #         'net': net.state_dict(),
    #         'acc': acc,
    #         'epoch': epoch,
    #     }
    #     if not os.path.isdir('checkpoint'):
    #         os.mkdir('checkpoint')
    #     torch.save(state, './checkpoint/ckpt.pth')
    #     best_acc = acc

from losses import *
import csv

def main(args):
    # Model
    setup_seed(args.seed)
    print('==> Building model..')
    dimension = 512
    net = ResNet18(dimension)
    net = net.to(device)

    if device == 'cuda':
        # net = torch.nn.DataParallel(net)
        cudnn.benchmark = True

    with open(args.output, 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile,)

        criterion = get_loss(args.loss,dimension,10,args).to(device)
        net.loss= criterion
        print(criterion)
        optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)

        pos = torch.Tensor([0.42,0.72])
        step_scheduler=MultiStepLR(optimizer,(pos*args.epochs).long().tolist(),gamma=0.1)
        for epoch in range(args.epochs):
            train_loss,train_acc=train(epoch,net,criterion,optimizer)
            test_loss,test_acc=test(epoch,net,criterion,optimizer)
            step_scheduler.step(epoch)
            spamwriter.writerow([epoch,train_loss,train_acc,test_loss,test_acc])
            csvfile.flush()

if __name__ == '__main__':
    freeze_support()
    parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
    parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
    parser.add_argument('-s', default=10, type=float)
    parser.add_argument('-m', default=0.1, type=float)
    parser.add_argument('--epochs', '-e', type=int, default=90)
    parser.add_argument('--loss', type=str, default='soft')
    parser.add_argument('--data', type=str, default="data")
    parser.add_argument('--seed', type=int, default="113")
    parser.add_argument('--output', type=str, default="result.csv")
    args = parser.parse_args()
    main(args)


